package com.atguigu.tingshu.account.service.impl;

import cn.hutool.core.lang.UUID;
import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.vo.account.RechargeInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class RechargeInfoServiceImpl extends ServiceImpl<RechargeInfoMapper, RechargeInfo> implements RechargeInfoService {

	@Autowired
	private RechargeInfoMapper rechargeInfoMapper;
	@Autowired
	private UserAccountService userAccountService;

	@Override
	public RechargeInfo findRechargeInfoByOrderNo(String orderNo) {
		LambdaQueryWrapper<RechargeInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(RechargeInfo::getOrderNo, orderNo);
		RechargeInfo rechargeInfo = this.getOne(lambdaQueryWrapper);
		return rechargeInfo;
	}

	@Override
	public void rechargePaySuccess(String orderNo) {
		LambdaQueryWrapper<RechargeInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(RechargeInfo::getOrderNo,orderNo);
		RechargeInfo rechargeInfo = this.getOne(lambdaQueryWrapper);
		if (SystemConstant.ORDER_STATUS_PAID.equals(rechargeInfo.getRechargeStatus()))return;

		rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_PAID);
		this.updateById(rechargeInfo);

		userAccountService.addUserAmount(rechargeInfo) ;
	}

	@Override
	public String submitRecharge(RechargeInfoVo rechargeInfoVo) {
		// 获取当前登录用户的id
		Long userId = AuthContextHolder.getUserId();

		// 生成订单的编号
		String orderNo = UUID.randomUUID().toString().replace("-", "");

		// 构建RechargeInfo对象，封装要保存的数据
		RechargeInfo rechargeInfo = new RechargeInfo() ;
		rechargeInfo.setUserId(userId);
		rechargeInfo.setOrderNo(orderNo);
		rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_UNPAID);
		rechargeInfo.setRechargeAmount(rechargeInfoVo.getAmount());
		rechargeInfo.setPayWay(rechargeInfoVo.getPayWay());

		// 保存数据
		rechargeInfoMapper.insert(rechargeInfo) ;

		return orderNo ;
	}

}
